package com.mydesignpattern.beijing.future.future;


import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

public class FutureTest {

    interface Data {
        List<Student> getList(String str);
    }

    class RealData implements Data{
        private List<Student> list = null;

        public RealData(String str){
            List<Student> list = new ArrayList<>();
            try {
                System.out.println("根据条件："+str+"查询学生list");
                Thread.sleep(5000);
                list.add(new Student("1","jack1","21","boy"));
                list.add(new Student("2","jack2","22","boy"));
                list.add(new Student("3","jack3","23","boy"));
                list.add(new Student("4","jack4","24","boy"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.list = list;
        }

        @Override
        public List<Student> getList(String str) {
            return list;
        }
    }

    class FutureData implements Data{
        private boolean ready = false;
        private RealData data = null;

        public synchronized void setData(RealData data){
            if(ready){
                return ;
            }
            this.data = data;
            ready = true;
            System.out.println("查询真是数据并回填完毕，唤醒所有线程");
            notifyAll();
        }

        @Override
        public synchronized List<Student> getList(String str) {
            System.out.println(Thread.currentThread().getName()+"获取列表：");
            if(!ready){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return data.getList(str);
        }
    }

    //测试
    @Test
    public void myFutureTest(){
        //客户端要根据条件查询data中的List<Student>
        FutureData data = new FutureData();
        String cond = "score > 95";
        new Thread(new Runnable() {
            @Override
            public void run() {
                data.setData(new RealData(cond));
            }
        }).start();

        System.out.println(cond +"的学生是："+data.getList(cond));
    }
}
